//
//  tucici
//
//  Created by tucici on 2017/11/26.
//  Copyright © 2017年 tucici. All rights reserved.
//

#import "XOWMZFController.h"
#import "TCCIAP.h"
#import "XOWMzfshitu.h"
#import "XOWMProduct.h"
#import "XOWMWebView.h"
#import "XOWMRequest.h"
#import <StoreKit/StoreKit.h>

@interface XOWMZFController ()<YJDzfshituDelegate, YJDWebViewDelegate,YJDRequestDelegate>
@property (nonatomic, strong) XOWMzfshitu *zfshitu;
@property (nonatomic, strong) XOWMWebView *webView;
@property (nonatomic, strong) XOWMProduct *product;
@property (nonatomic, strong) XOWMRequest *request;
@end

@implementation XOWMZFController
- (void)viewDidLoad {
    [super viewDidLoad];
    [CCDB db];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(yjd_zfNotification:) name:TCCIAPNotification object:nil];
    // Do any additional setup after loading the view.
}


- (XOWMzfshitu *)zfshitu
{
    if (!_zfshitu)
    {
        _zfshitu = [[XOWMzfshitu alloc]init];
        _zfshitu.delegate = self;
        [self.view addSubview:_zfshitu];
        CGFloat width = SCREEN_MIN_LENGTH - 20;
        _zfshitu.c_center.equal(self.view);
        _zfshitu.c_size.equal(CGSizeMake(width, width));
    }
    return _zfshitu;
}

- (XOWMWebView *)webView
{
    if (!_webView)
    {
        _webView = [[XOWMWebView alloc]init];
        _webView.delegate = self;
        [self.view addSubview:_webView];
        _webView.c_edges.equal(UIEdgeInsetsZero);
    }
    return _webView;
}

- (XOWMRequest *)request
{
    if (!_request)
    {
        _request = [[XOWMRequest alloc]init];
        _request.delegate = self;
    }
    return _request;
}

- (void)yjd_zunbeizf:(XOWMProduct *)product
{
    //进行必传参数判断，如果没有，则弹出提示
    if (!product.goodsID || [product.goodsID length] < 1)[CCAlert showMessage:@"请填写商品内购ID" hidden:nil];
    else if (!product.goodsTitle || [product.goodsTitle length] < 1) [CCAlert showMessage:@"请填写商品标题" hidden:nil];
    else if (!product.goodsPrice || [product.goodsPrice length] < 1) [CCAlert showMessage:@"请填写商品价格" hidden:nil];
    else if (!product.notifyURL || [product.notifyURL length] < 1) [CCAlert showMessage:@"请填写后台支付通知接口" hidden:nil];
    else if (!product.serverID || [product.serverID length] < 1) [CCAlert showMessage:@"请填写游戏区服ID" hidden:nil];
    else if (!product.serverName || [product.serverName length] < 1) [CCAlert showMessage:@"请填写游戏区服名称" hidden:nil];
    else if (!product.roleID || [product.roleID length] < 1) [CCAlert showMessage:@"请填写游戏角色ID" hidden:nil];
    else if (!product.roleName || [product.roleName length] < 1) [CCAlert showMessage:@"请填写游戏角色名称" hidden:nil];
    else if (!product.roleLevel ||  [product.roleLevel length] < 1 || ![product.roleLevel yjd_isNumber])[CCAlert showMessage:@"请正确填写游戏角色等级" hidden:nil];
    else
    {
        [self yjd_startHUDDDD];
        self.product = nil;
        self.product = product;
        if ([[XOWMHelper shareHelp].country isEqualToString:@"美国"] || [[XOWMHelper shareHelp].country isEqualToString:@""])
        {
            self.product.fzfs = @"1";
            BOOL doing = [TCCIAP yjd_isDoing];
            if (doing)
            {
                [CCHud stopHud];
                [CCAlert showMessage:@"正在支付..." hidden:^{
                    [CCHud startHud];
                }];
                return;
            }
        }
        [self.request yjd_preparezf:self.product];
    }
}

- (void)yjd_showWebView:(NSString *)url
{
    self.webView.hidden = NO;
    self.zfshitu.hidden = YES;
    [self.webView yjd_show:url];
}

- (void)yjd_zhanshizffs:(NSString *)string zffg:(NSString *)zffg zftp:(NSString *)zftp
{
    self.zfshitu.hidden = NO;
    self.webView.hidden = YES;
    [self.zfshitu yjd_zhanshi:string mz:zffg tp:zftp];
}

- (void)yjd_dismiss
{
    [self yjd_stopHUDDDDD];
    [self dismissViewControllerAnimated:YES completion:^{
        [self.webView removeFromSuperview];
        self.zfshitu = nil;
        self.webView = nil;
    }];
}

- (void)yjd_startHUDDDD
{
    [CCHud startHud];
    [self.zfshitu yjd_closeEnterBtn];
}

- (void)yjd_stopHUDDDDD
{
    [CCHud stopHud];
    [self.zfshitu yjd_openEnterBtn];
}


#pragma mark - YJDzfshituDelegate
- (void)yjd_actionWithSubViewEvent:(YJDzfshituEvent)event
{
    if (event == YJDzfshituEventBack)
    {
        [self yjd_dismiss];
    }
}

- (void)yjd_actionForSelectWay:(int)fzfs
{
    [self yjd_startHUDDDD];
    self.product.fzfs = [NSString stringWithFormat:@"%d",fzfs];
    [self.request yjd_preparezf:self.product];
}

#pragma mark - YJDWebViewDelegate
- (void)yjd_actionForWebView
{
    [self yjd_dismissWithMessage:nil];
}
#pragma mark - YJDRequestDelegate
- (void)yjd_didRequestWithReceiveData:(NSDictionary *)dict
{
    [self yjd_stopHUDDDDD];
    if(!dict)
        return;
    int code = [[dict valueForKey:@"code"] intValue];
    NSString *info = [dict valueForKey:@"info"];
    //成功
    if (code == 100 )
    {
        
        int ID = [[dict valueForKey:@"channelid"] intValue];
        switch (ID) {
            case 0://自定义
                if ([[[dict valueForKey:@"channelids"] componentsSeparatedByString:@","] count] == 1
                    && [[[dict valueForKey:@"channelids"] componentsSeparatedByString:@","][0] intValue] == 1)
                {
                    self.product.jiaoyiHao = [dict valueForKey:@"payid"];
                    [TCCIAP yjd_zf:self.product.jiaoyiHao goodsID:self.product.goodsID];
                    return;
                }
                
                [self yjd_pop];
                [self.zfshitu yjd_productInfo:_product];
                [self yjd_zhanshizffs:[dict valueForKey:@"channelids"] zffg:[dict valueForKey:@"channelnames"] zftp:[dict valueForKey:@"channelicons"]];
                break;
            case 1://
                [self yjd_startHUDDDD];
                self.product.jiaoyiHao = [dict valueForKey:@"payid"];
                [TCCIAP yjd_zf:self.product.jiaoyiHao goodsID:self.product.goodsID];
                break;
            case 2://
            case 3://
                [self yjd_pop];
                [self yjd_showWebView:[dict valueForKey:@"weburl"]];
                break;
            case 4://测试，无需支付
                break;
            default:
                break;
        }
    }
    //失败
    else
    {
        [CCAlert showMessage:[NSString stringWithFormat:@"code:%d(%@)",code,info] title:@"错误" enter:nil];
    }
    
}

- (void)yjd_zfNotification:(NSNotification *)notify
{
    int status = [[notify.userInfo valueForKey:@"status"] intValue];
    NSString *info = [notify.userInfo valueForKey:@"info"];
    switch (status)
    {
        case TCCIAPStatusWillRequest://将要开始内购
            [self yjd_startHUDDDD];
            break;
        case TCCIAPStatusSuccessRequest://内购成功
            [self yjd_dismissWithMessage:nil];
            break;
        case TCCIAPStatusNothingRequest://appstore没有注册该商品
            [self yjd_dismissWithMessage:@"当前商城没有该商品"];
            break;
        case TCCIAPStatusNonSupportRequest://当前设备不支持内购
            [self yjd_dismissWithMessage:@"当前设备不支持苹果内购"];
            break;
        case TCCIAPStatusCancelRequest://取消交易
            if (info)
                [self yjd_dismissWithMessage:info];
            else
                [self yjd_dismissWithMessage:@"取消交易"];
            break;
        case TCCIAPStatusDoingRequest:
            [CCHud stopHud];
            [CCAlert showMessage:@"正在支付..." hidden:^{
                [CCHud startHud];
            }];
            break;
        case TCCIAPStatusFailRequest:
            [CCHud stopHud];
            [CCAlert showMessage:info hidden:nil];
            break;
        default:
            break;
    }
}

- (void)yjd_dismissWithMessage:(NSString *)message
{
    [self yjd_stopHUDDDDD];
    if (!message)//交易动作完成message为nil
    {
        [self yjd_dismiss];
        if (self.delegate && [self.delegate respondsToSelector:@selector(yjd_didReceiveFromYJDZFController:)])
        {
            [self.delegate yjd_didReceiveFromYJDZFController:nil];
        }
    }
    else{
        [CCAlert showMessage:message title:@"错误" enter:^{
            [self yjd_dismiss];
        }];
    }
}

- (void)verificationWithRespons:(XOWMProduct *)product
{
    [self yjd_stopHUDDDDD];
    if (self.delegate && [self.delegate respondsToSelector:@selector(yjd_didReceiveFromYJDZFController:)])
    {
        [self.delegate yjd_didReceiveFromYJDZFController:product];
    }
    
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.zfshitu.cancelBtn.content = ([XOWMHelper shareHelp].style == XOWMPlatformStyleImage)?@"yjd_取消_Btn":@"cancel";
    self.zfshitu.imageView.imageName = ([XOWMHelper shareHelp].style == XOWMPlatformStyleImage)?@"yjd_背景":@"";
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */


- (void)sp_getUsersMostLikedSuccess {
    NSLog(@"Continue");
}
@end
